package system

import (
	"gitee.com/baal1990/epidemic/global"
	response "gitee.com/baal1990/epidemic/model/common/response_dfitc"
	"gitee.com/baal1990/epidemic/model/epidemic"
	"gitee.com/baal1990/epidemic/utils/msgsms"
	"gitee.com/baal1990/epidemic/utils/token"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type Dfitc struct {
}

// MsgCode 发送短信验证码
// 模板id: 41145df187524230852fd43db7d1cf04
func (d *Dfitc) MsgCode(c *gin.Context) {
	mobileRsa := c.PostForm("mobile")
	if mobileRsa == "" {
		global.GVA_LOG.Sugar().Error("参数错误，mobile=", mobileRsa)
		response.FailWithMessage("参数错误", c)
		return
	}
	// 解密
	mobileByte, err := global.AsymmetricCrypto.DecryptWithPrvKeyFromBase64(mobileRsa)
	if err != nil {
		global.GVA_LOG.Sugar().Error("参数错误", err)
		response.FailWithMessage("参数错误", c)
		return
	}
	mobile := string(mobileByte)
	code, err := global.MsgCodeGenerator.Gen(mobile)
	if err != nil {
		global.GVA_LOG.Sugar().Error("生成验证码失败", err)
		response.FailWithMessage(err.Error(), c)
		return
	} else {
		if err := msgsms.SendMsg([]string{mobile}, "55ab415b225b40fd87362611d86b1acb", "csms18083014", code); err != nil {
			global.GVA_LOG.Sugar().Error("发送验证码失败", err)
			response.FailWithMessage("发送验证码失败", c)
		} else {
			global.GVA_LOG.Sugar().Infof("发送验证码成功:手机号为%s,验证码为%s", mobile, code)
			response.OkWithMessage("发送成功", c)
		}
	}
}

// Login 登录
func (d *Dfitc) Login(c *gin.Context) {
	mobileRsa := c.PostForm("mobile")
	if mobileRsa == "" {
		global.GVA_LOG.Sugar().Error("参数错误，mobile=", mobileRsa)
		response.FailWithMessage("参数错误", c)
		return
	}
	deviceType := c.PostForm("device")
	if deviceType == "" {
		global.GVA_LOG.Sugar().Error("参数错误，device=", deviceType)
		response.FailWithMessage("参数错误", c)
		return
	}
	// 解密
	mobileByte, err := global.AsymmetricCrypto.DecryptWithPrvKeyFromBase64(mobileRsa)
	if err != nil {
		global.GVA_LOG.Sugar().Error("参数错误", err)
		response.FailWithMessage("参数错误", c)
		return
	}
	mobile := string(mobileByte)
	code := c.PostForm("code")
	if err = global.MsgCodeGenerator.Check(mobile, code); err != nil {
		global.GVA_LOG.Sugar().Error("登录失败，mobile=", mobile, err)
		response.FailWithMessage(err.Error(), c)
		return
	} else {
		user := epidemic.EpidemicUser{}
		if err := global.GVA_DB.Table("epidemic_user").Where("mobile=?", mobile).Find(&user).Error; err != nil {
			global.GVA_LOG.Sugar().Error("登录失败，mobile=", mobile, err)
			response.FailWithMessage("登录失败", c)
			return
		}
		if user.ID == 0 {
			//用户不存在
			if deviceType == global.DICT_DVICE_TYPE_MOBILE {
				tmp := epidemic.EpidemicUser{
					Mobile:    mobile,
					BirthDate: "2006-01-02",
					Status:    "1",
				}
				if err = global.GVA_DB.Save(&tmp).Error; err != nil {
					global.GVA_LOG.Sugar().Error("登录失败，mobile=", mobile, err)
					response.FailWithMessage("登录失败", c)
					return
				}
				if err := global.GVA_DB.Table("epidemic_user").Where("mobile=?", mobile).Find(&tmp).Error; err != nil {
					global.GVA_LOG.Sugar().Error("登录失败，mobile=", mobile, err)
					response.FailWithMessage("登录失败", c)
					return
				}
				user.ID = tmp.ID
			} else {
				global.GVA_LOG.Sugar().Error("用户不存在，mobile=", mobile)
				response.FailWithMessage("用户不存在", c)
				return
			}
		}
		if deviceType != global.DICT_DVICE_TYPE_MOBILE {
			if user.Role != global.DICT_ROLES_SUPER && user.Role != global.DICT_ROLES_MANAGER {
				global.GVA_LOG.Sugar().Error("非管理账号")
				response.FailWithDetailedWithErrorCode(response.USER_ROLES_ERR, nil, "账号权限不足", c)
				return
			}
		}
		// 生成token并返回
		accessExpire := time.Duration(global.GVA_CONFIG.JWT.AccessExpiresTime) * time.Second
		refreshExpire := time.Duration(global.GVA_CONFIG.JWT.RefreshExpiresTime) * time.Minute
		jwt, err := token.NewToken(strconv.Itoa(user.ID), accessExpire, refreshExpire)
		if err != nil {
			global.GVA_LOG.Sugar().Error("登录失败，mobile=", mobile, err)
			response.FailWithMessage("登录失败", c)
			return
		}
		response.OkWithDetailed(jwt, "登录成功", c)
	}
}

// RefreshToken 刷新token
func (d *Dfitc) RefreshToken(c *gin.Context) {
	xToken := c.GetHeader("x-token")
	t := token.Token{RefreshToken: xToken}
	payload, err := t.ValidateRefreshToken()
	if err != nil {
		global.GVA_LOG.Sugar().Error("非法x-token", err)
		response.FailWithDetailedWithErrorCode(response.ERROR_TOKEN_REFRESH, nil, "刷新失败", c)

		return
	}
	accessExpire := time.Duration(global.GVA_CONFIG.JWT.AccessExpiresTime) * time.Second
	refreshExpire := time.Duration(global.GVA_CONFIG.JWT.RefreshExpiresTime) * time.Minute
	t, err = t.Refresh(payload.UerId, accessExpire, refreshExpire)
	if err != nil {
		global.GVA_LOG.Sugar().Error("刷新失败", err)
		response.FailWithDetailedWithErrorCode(response.ERROR_TOKEN_REFRESH, nil, "刷新失败", c)
		return
	}
	response.OkWithDetailed(t, "刷新成功", c)
}
